<style lang="scss" scoped>
.login {
  padding: 10px;
  background-color: white;
}
</style>

<template>
  <div>
    <div class="login">
      <el-form :model="formData" :rules="rules" ref="formRef">
        <el-form-item label="账号" prop="username">
          <el-input v-model="formData.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="formData.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin">登陆</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormRules, FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import 'element-plus/es/components/message/style/css'
import axios from 'axios'
import { debounce } from '@/utils'
import { useUserHooks } from '@/stores/user'
import { useRoute, useRouter } from 'vue-router'

interface FromDataState {
  username: string
  password: string
}

const router = useRouter()
const route = useRoute()
// form 实例
const formRef = ref<FormInstance>()
// 登陆数据
const formData = ref<FromDataState>({
  username: '张三',
  password: '123456'
})
// 验证规则
const rules = reactive<FormRules<FromDataState>>({
  username: [{ required: true, message: '账号不可以为空' }],
  password: [{ required: true, message: '密码不可以为空' }]
})

// 登录函数
const handleLogin = debounce(() => {
  formRef.value?.validate().then(async () => {
    // 请求登录接口
    const resp = await axios({
      url: 'login',
      method: 'post',
      data: formData.value
    })
    const { code, data, message } = resp.data
    if (code === 200) {
      // 存储用户信息
      useUserHooks().LoginSuccess(data)
      localStorage.setItem('token', data.token)
      localStorage.setItem('refreshToken', data.refreshToken)
      ElMessage({ type: 'success', message })
      // 进入首页
      if (route.path === '/login') {
        router.push({ path: '/' })
      }
    } else {
      ElMessage({ type: 'error', message })
    }
  })
}, 400)
</script>

<script lang="ts">
export default {
  name: 'LoginView'
}
</script>
